/**
 * Copyright (C) 2010-2016 eBusiness Information, Excilys Group
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed To in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package org.ohosannotations.api.view;

import java.util.LinkedHashSet;
import java.util.Set;

/**
 * 视图改变通知
 *
 * @since 2021-07-20
 */
public class OnViewChangedNotifier {
    private static OnViewChangedNotifier currentNotifier;
    private final Set<OnViewChangedListener> listeners = new LinkedHashSet<>();

    /**
     * 取代通知
     *
     * @param notifier 视图改变通知
     * @return OnViewChangedNotifier 视图改变通知
     */
    public static OnViewChangedNotifier replaceNotifier(OnViewChangedNotifier notifier) {
        OnViewChangedNotifier previousNotifier = currentNotifier;
        currentNotifier = notifier;
        return previousNotifier;
    }

    /**
     * 注册视图改变监听
     *
     * @param listener 视图改变监听
     */
    public static void registerOnViewChangedListener(OnViewChangedListener listener) {
        if (currentNotifier != null) {
            currentNotifier.listeners.add(listener);
        }
    }

    /**
     * 通知视图改变
     *
     * @param hasViews 视图
     */
    public void notifyViewChanged(HasViews hasViews) {
        for (OnViewChangedListener listener : listeners) {
            listener.onViewChanged(hasViews);
        }
    }
}
